#!/bin/sh
# Prepare systemd source package in current directory for testing an upstream
# commit, branch, or PR, without Debian patches. This replaces everything
# except the debian/ directory with an upstream checkout.
# NEVER run this in your actual packaging work directory! This is only meant
# for upstream CI.
#
# Author: Martin Pitt <martin.pitt@ubuntu.com>

set -eu
test -x debian/rules
if [ -z "${TEST_UPSTREAM:-}" ]; then
    echo "Not in upstream testing mode. Do *not* run this script unless you know what you are doing." >&2
    exit 1
fi
if [ -n "${UPSTREAM_PULL_REQUEST:-}" ]; then
    FETCH="git fetch -fu origin refs/pull/$UPSTREAM_PULL_REQUEST/head:pr"
    CO='git checkout pr'
    DESC="PR #$UPSTREAM_PULL_REQUEST"
elif [ -n "${UPSTREAM_HEAD:-}" ]; then
    FETCH=''
    CO="git checkout $UPSTREAM_HEAD"
    DESC="$UPSTREAM_HEAD"
else
    echo "WARNING: $0: Neither UPSTREAM_PULL_REQUEST nor UPSTREAM_HEAD set, ignoring" >&2
    exit 0
fi

mkdir -p debian/tmp
(cd debian/tmp
 git clone https://github.com/systemd/systemd.git upstream || (rm -rf upstream; sleep 60; git clone https://github.com/systemd/systemd.git upstream)
 cd upstream
 $FETCH
 $CO
 git config user.email "invalid@example.com"
 git config user.name "Merge dummy user"
 git rebase master)
UPSTREAM_VER=$(cd debian/tmp/upstream; git describe | sed 's/^v//')

# clean out original upstream sources and patches
find -mindepth 1 -maxdepth 1 -name debian -prune -o -print0 | xargs -0n1 rm -rf
rm -rf debian/patches

# replace with checkout
mv debian/tmp/upstream/* .
rm -rf debian/tmp

# craft changelog
cat << EOF > debian/changelog.new
systemd (${UPSTREAM_VER}-0) UNRELEASED; urgency=low

  * Automatic build from upstream $DESC

 -- systemd test <pkg-systemd-maintainers@lists.alioth.debian.org>  $(date -R)

EOF
cat debian/changelog >> debian/changelog.new
mv debian/changelog.new debian/changelog

# disable tests which are not for upstream
sed -i '/# NOUPSTREAM/ q' debian/tests/control
